package cn.tannn.cat.file.server.dao;

import cn.tannn.cat.file.sdk.enums.StorageDict;
import cn.tannn.cat.file.sdk.enums.StorageMaster;
import cn.tannn.cat.file.server.entity.FileStorageConfig;
import cn.tannn.jdevelops.jpa.repository.JpaBasicsRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 存储器配置
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2024/3/7 14:10
 */
public interface FileStorageConfigDao extends JpaBasicsRepository<FileStorageConfig, Long> {


    /**
     * 更新master设置
     * @param master StorageMaster
     * @param id id
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query("update FileStorageConfig dc set dc.master = :master where  dc.id = :id ")
    void updateMaster(@Param("master") StorageMaster master, @Param("id") Long id);

    /**
     *  设置 slave [指定设置]
     * @param ids 指定为slave的id
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query("update FileStorageConfig dc set dc.master = 0 where  dc.id in (:ids) ")
    void changeSlave(@Param("ids") List<Long> ids);

    /**
     *  设置 slave [设置全部为slave]
     * @param id 排除这个id不被设置
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query("update FileStorageConfig dc set dc.master = 0 where  dc.id != :id ")
    void changeSlave(@Param("id") Long id);


    /**
     * 查询存储器配置
     *
     * @param name 配置名
     * @return true 存在
     */
    Optional<FileStorageConfig> findByName(String name);


    /**
     * 获取 master 配置
     * @return FileConfig
     */
    @Query("select fc from FileStorageConfig fc where " +
            "fc.master = cn.tannn.cat.file.sdk.enums.StorageMaster.MASTER ")
    Optional<FileStorageConfig> findMaster();


    /**
     * 获取所有地配置
     * @param storage {@link StorageDict} [10:LOCAL, 20:MINIO, 30:S3, 40:qiniu, 50: aliyun, 60: ftp]
     * @return FileConfig
     */
    @Query("select fc from FileStorageConfig fc where " +
            "fc.storage = :storage ")
    List<FileStorageConfig> findConfig(@Param("storage") String storage);

}
